%matplotlib inline
import pandas as pd
import numpy as np
import math
import scipy
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
pio.renderers.default = "plotly_mimetype+notebook"
For this excercise, we have written the following code to load the stock dataset built into plotly express.
stocks = px.data.stocks()
stocks.head()
Select a stock and create a suitable plot for it. Make sure the plot is readable with relevant information, such as date, values.
# YOUR CODE HERE
x = stocks['date']
y = stocks['GOOG']
fig, ax = plt.subplots(figsize=(15,9))
ax.plot(x,y)
ax.set_xticks(np.arange(0, len(x)+1, 14))
ax.set_title('Google stock')
ax.set_xlabel('date')
ax.set_ylabel('Stock value')
plt.show()
You've already plot data from one stock. It is possible to plot multiples of them to support comparison.
To highlight different lines, customise line styles, markers, colors and include a legend to the plot.
# YOUR CODE HERE
x = stocks['date']
y1 = stocks['GOOG']
y2 = stocks['AAPL']
y3 = stocks['AMZN']
y4 = stocks['FB']
y5 = stocks['NFLX']
y6 = stocks['MSFT']
fig, ax = plt.subplots(figsize=(15,9))
ax.plot(x,y1, linestyle='dashdot', marker='o')
ax.plot(x,y2, linestyle='solid', marker='p')
ax.plot(x,y3, linestyle='dotted', marker='v')
ax.plot(x,y4, linestyle='dashed', marker='<')
ax.plot(x,y5, marker='>')
ax.plot(x,y6, marker='s')
ax.set_xticks(np.arange(0, len(x)+1, 14))
ax.set_title('Stocks')
ax.set_xlabel('date')
ax.set_ylabel('Stock value')
plt.legend()
plt.show()
First, load the tips dataset
tips = sns.load_dataset('tips')
tips.head()
Let's explore this dataset. Pose a question and create a plot that support drawing answers for your question.
Some possible questions:
#Do most people tip at lunchtime or dinnertime?
g = sns.FacetGrid(tips, hue='time')
g.map(sns.scatterplot, 'total_bill', 'tip')
g.add_legend()
plt.show()
Redo the above exercises (challenges 2 & 3) with plotly express. Create diagrams which you can interact with.
Hints:
# YOUR CODE HERE
fig = px.line(stocks, x="date", y = stocks.columns)
fig.show()
#Do most people tip at lunchtime or dinnertime depending on the total bill?
fig2 = px.scatter(tips, x="total_bill", y = ["tip"], color="time")
fig2.show()
Recreate the barplot below that shows the population of different continents for the year 2007.
Hints:
#load data
df = px.data.gapminder()
df.head()
# YOUR CODE HERE
df_2007 = df.query('year==2007')
a = df_2007.groupby('continent')
df_2007_new = df_2007.groupby('continent').sum()
fig = px.bar(df_2007_new, x="pop", y=df_2007_new.index , color =df_2007_new.index, orientation='h', text_auto = True)
fig.update_yaxes(categoryorder="min ascending")
fig.show()